<?php
namespace app\api\model;

use app\model\Base;
use think\facade\Db;
use think\facade\Log;

class Orders extends Base
{
    public static $v2_limit_one = 399000;//199500;
    public static $v2_limit_two = 399000;

    public static $base_level_reward = 4000;
    public static $level_reward2_rate = 10;//goods type是2时候的比例
    public static $base_same_level_reward = 500;

    public static $director_reward = 1000;//董事补贴

    public static $honor_director_reward = 500;//荣誉董事补贴

    public static function afterShopping($orders_id, $user_id, $alias, $type){
        //各种积分购物后
        $orders_info = self::find($orders_id);
        $goods_num = $orders_info['goods_num'];

        $user_info = User::where('id', $user_id)->find();
        $total_amount = $orders_info['total_amount'];

        //级差奖励
        $user_parent_ids_str = str_replace('|', ',', substr_replace(substr_replace($user_info['parent_ids'], '', 0, 1), '', -1, 1));
        $parent_ids_array = User::field('id, level_id, virtual_level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
            ->order(Db::raw('field(id, ' . $user_parent_ids_str . ')'))
            ->select();
        $level_reward_array = [];
        $level_reward_array['level'] = [];
        $level_reward_array['same_level'] = [];
        if($user_info['virtual_level_id'] <= 5)
        {
            //只有合伙人以下级别下单 才有等级奖励
            $level_reward_array = self::levelReward($user_info['virtual_level_id'], $parent_ids_array, $goods_num, $orders_info['goods_id']);
        }

        $director_reward_array = [];
        //董事补贴
        if($director_reward_user = User::field('id, level_id, virtual_level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
            ->where('virtual_level_id', 6)
            ->order(Db::raw('field(id, ' . $user_parent_ids_str . ')'))
            ->find())
        {
            $director_reward_array[] = [
                'user_id'=>$director_reward_user['id'],
                'level_id'=>6,
                'reward'=>bcmul(self::$director_reward, $goods_num),
            ];
        }

        //荣誉董事补贴
//        $honor_director_reward_array = self::honorDirectorReward($goods_num);

        $level_id = $user_info['level_id'];
        $virtual_level_id = $user_info['virtual_level_id'];
        if($user_info['level_id'] == 0)
        {
            //静态升级
            $level_id = self::staticLevelUp($user_id, $total_amount);
        }
        if($virtual_level_id < $level_id)
        {
            $virtual_level_id = $level_id;
        }

        Db::startTrans();
        try {
            foreach ($level_reward_array['level'] as $level)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($level['user_id'], $level['reward'], 'score', 'shop_level_' . $level['level_id'], '【' . $orders_info['id'] . '】');
            }
            foreach ($level_reward_array['same_level'] as $same_level)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($same_level['user_id'], $same_level['reward'], 'score', 'shop_same_level_' . $same_level['level_id'], '【' . $orders_info['id'] . '】');
            }
            foreach ($director_reward_array as $director)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($director['user_id'], $director['reward'], 'score', 'shop_director_allowances', '【' . $orders_info['id'] . '】');
            }
//            foreach ($honor_director_reward_array as $honor_director)
//            {
//                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
//                User::induce($honor_director['user_id'], $honor_director['reward'], 'score', 'shop_honor_director_allowances');
//            }

            User::where('id', $user_id)
                ->inc('spending', $total_amount)
                ->inc('spending_num', $goods_num)
                ->update([
                    'level_id'=>$level_id,
                    'virtual_level_id'=>$virtual_level_id
                ]);

            User::whereIn('id', $user_parent_ids_str)
                ->inc('performance', $total_amount)
                ->inc('performance_num', $goods_num)
                ->update();

            //deduce($userId, $amount, $alias = 'money', $level1 = 0, $level2 = 0, $des = '')
            User::deduce($user_id, $total_amount, $alias, $type, '【' . $orders_info['id'] . '】');

            EverydayPerformance::createRecord($user_id, $orders_info);

            Orders::where('id', $orders_id)->update([
                'status'=>'payed',
                'pay_type'=>$alias,
                'update_time'=>date('Y-m-d H:i:s'),
                'pay_time'=>date('Y-m-d H:i:s'),
            ]);

            Db::commit();
        } catch (\Exception $exception) {

            Db::rollback();

            Log::error('afterShopping:'.json_encode(['message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], JSON_UNESCAPED_UNICODE));
            return false;
        }

        return true;
    }

    public static function levelReward($user_level_id, $parent_ids_array, $goods_num, $goods_id)
    {
        //级别奖励
        //[0=>普通,1=>会员,2=>县代,3=>市代,4=>省代,5=>合伙人]
        $start_level_id = $user_level_id;
        $reward = 0;
        $arr = [];
        $arr['level'] = [];
        $arr['same_level'] = [];

        $goods_info = Goods::find($goods_id);
        $level_reward = 0;
        switch ($goods_info['type'])
        {
            case 1:
                $level_reward = self::$base_level_reward;
                break;
            case 2:
                $level_reward = bcdiv(bcmul($goods_info['sale_amount'], self::$level_reward2_rate), Base::$hundred);
                break;
        }

        foreach ($parent_ids_array as $parent)
        {
            if($parent['virtual_level_id'] > $start_level_id)
            {
                $parent_level_id = $parent['virtual_level_id'] >= 5 ? 5 : $parent['virtual_level_id'];
                $diff_level = $parent_level_id - $start_level_id;
                $reward = bcmul(bcmul($level_reward, $diff_level), $goods_num);
                $arr['level'][] = [
                    'user_id'=>$parent['id'],
                    'level_id'=>$parent_level_id,
                    'reward'=>$reward,
                ];
                if($parent['virtual_level_id'] > 2 && $parent['virtual_level_id'] < 6)
                {
                    $user_parent_ids_str = str_replace('|', ',', substr_replace(substr_replace($parent['parent_ids'], '', 0, 1), '', -1, 1));
                    if($same_level_user = User::field('id, level_id, virtual_level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
                        ->where('virtual_level_id', $parent['virtual_level_id'])
                        ->order(Db::raw('field(id, ' . $user_parent_ids_str . ')'))
                        ->find())
                    {
                        $arr['same_level'][] = [
                            'user_id'=>$same_level_user['id'],
                            'level_id'=>$parent['virtual_level_id'],
                            'reward'=>bcmul(self::$base_same_level_reward, $goods_num)
                        ];
                    }
                }

                $start_level_id = $parent_level_id;
            }
//            elseif ($parent['virtual_level_id'] == $start_level_id)
//            {
//                $arr['same_level'][] = [
//                    'user_id'=>$parent['id'],
//                    'level_id'=>$parent['virtual_level_id'],
//                    'reward'=>bcmul(self::$base_same_level_reward, $goods_num)
//                ];
//                $start_level_id = $parent_level_id;
//            }
            if($start_level_id == 5)
            {
                //已经是合伙人
                break;
            }
        }
        return $arr;
    }

    public static function honorDirectorReward($goods_num)
    {
        //荣誉董事补贴
        $user_lists = User::where('level_id', 7)->select();
        $count = count($user_lists);
        $amount = 0;
        $arr = [];
        if($count > 0)
        {
            $amount = bcdiv(bcmul(self::$honor_director_reward, $goods_num), $count);
            foreach ($user_lists as $lists)
            {
                $arr[] = [
                    'user_id'=>$lists['id'],
                    'level_id'=>$lists['level_id'],
                    'reward'=>$amount
                ];
            }

        }
        return $arr;
    }

//    public static function sameLevelReward($user_level_id, $parent_ids_array, $goods_num)
//    {
//        //同级别奖励
//        //[0=>普通,1=>会员,2=>县代,3=>市代,4=>省代,5=>合伙人]
//        $reward = 0;
//        foreach ($parent_ids_array as $parent)
//        {
//            if($parent['level_id'] = $user_level_id)
//            {
//                $reward = bcmul(self::$base_same_level_reward, $goods_num);
//                break;
//            }
//        }
//    }


    public static function staticLevelUp($user_id, $amount)
    {
        //静态升级
        $level_id = 1;
        $user_info = User::where('id', $user_id)->find();
//        $after_spending = bcadd($user_info['spending'], $amount);

        if($amount >= self::$v2_limit_one || $user_info['performance'] >= self::$v2_limit_two)
        {
            $level_id = 2;
        }
//        if($user_info['performance'] >= self::$v2_limit_two)
//        {
//            $level_id = 2;
//        }
        return $level_id;
    }





    public function getStatusFormatAttr($value, $data)
    {
        $str = '';
        switch ($data['status'])
        {
            case 'paying':
                $str = "待付款";
                break;
            case 'payed':
                $str = "已支付";
                break;
        }
        return $str;
    }

    public function getCountAttr($value, $data)
    {
        return $data['goods_num'];
    }

    public function getParamsAttr($value, $data)
    {
        return [
            'id'=>$data['id']
        ];
    }

    public function getAddressFormatAttr($value, $data)
    {
        return $data['province_name'] . $data['city_name'] . $data['area_name'] . $data['address'];
    }

    public function ordersGoods()
    {
        return $this->hasOne(Goods::class, 'id', 'goods_id')->bind([
            'goods_cover'=>'cover',
            'amount'=>'sale_amount',
            'goods_title'=>'name',
        ]);
    }

    public static function afterShoppingOld($orders_id, $user_id, $alias, $type){
        //各种积分购物后
        $orders_info = self::find($orders_id);
        $goods_num = $orders_info['goods_num'];

        $user_info = User::where('id', $user_id)->find();
        $total_amount = $orders_info['total_amount'];

        //级差奖励
        $user_parent_ids_str = str_replace('|', ',', substr_replace(substr_replace($user_info['parent_ids'], '', 0, 1), '', -1, 1));
        $parent_ids_array = User::field('id, level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
            ->order(Db::raw('field(id, ' . $user_parent_ids_str . ')'))
            ->select();
        $level_reward_array = [];
        $level_reward_array['level'] = [];
        $level_reward_array['same_level'] = [];
        if($user_info['level_id'] < 5)
        {
            //只有合伙人以下级别下单 才有等级奖励
            $level_reward_array = self::levelReward($user_info['level_id'], $parent_ids_array, $goods_num, $orders_info['goods_id']);
        }

        $director_reward_array = [];
        //董事补贴
        if($director_reward_user = User::field('id, level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
            ->where('level_id', 6)
            ->order(Db::raw('field(id, ' . $user_parent_ids_str . ')'))
            ->find())
        {
            $director_reward_array[] = [
                'user_id'=>$director_reward_user['id'],
                'level_id'=>6,
                'reward'=>bcmul(self::$director_reward, $goods_num),
            ];
        }

        //荣誉董事补贴
//        $honor_director_reward_array = self::honorDirectorReward($goods_num);

        $level_id = $user_info['level_id'];
        if($user_info['level_id'] == 0)
        {
            //静态升级
            $level_id = self::staticLevelUp($user_id, $total_amount);
        }

        Db::startTrans();
        try {
            foreach ($level_reward_array['level'] as $level)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($level['user_id'], $level['reward'], 'score', 'shop_level_' . $level['level_id']);
            }
            foreach ($level_reward_array['same_level'] as $same_level)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($same_level['user_id'], $same_level['reward'], 'score', 'shop_same_level_' . $same_level['level_id']);
            }
            foreach ($director_reward_array as $director)
            {
                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
                User::induce($director['user_id'], $director['reward'], 'score', 'shop_director_allowances');
            }
//            foreach ($honor_director_reward_array as $honor_director)
//            {
//                //induce($user_id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
//                User::induce($honor_director['user_id'], $honor_director['reward'], 'score', 'shop_honor_director_allowances');
//            }

            User::where('id', $user_id)
                ->inc('spending', $total_amount)
                ->inc('spending_num', $goods_num)
                ->update([
                    'level_id'=>$level_id
                ]);

            User::whereIn('id', $user_parent_ids_str)
                ->inc('performance', $total_amount)
                ->inc('performance_num', $goods_num)
                ->update();

            //deduce($userId, $amount, $alias = 'money', $level1 = 0, $level2 = 0, $des = '')
            User::deduce($user_id, $total_amount, $alias, $type);

            EverydayPerformance::createRecord($user_id, $orders_info);

            Orders::where('id', $orders_id)->update([
                'status'=>'payed',
                'pay_type'=>$alias,
                'update_time'=>date('Y-m-d H:i:s'),
                'pay_time'=>date('Y-m-d H:i:s'),
            ]);

            Db::commit();
        } catch (\Exception $exception) {

            Db::rollback();

            Log::error('afterShopping:'.json_encode(['message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], JSON_UNESCAPED_UNICODE));
            return false;
        }

        return true;
    }

    public static function levelRewardOld($user_level_id, $parent_ids_array, $goods_num, $goods_id)
    {
        //级别奖励
        //[0=>普通,1=>会员,2=>县代,3=>市代,4=>省代,5=>合伙人]
        $start_level_id = $user_level_id;
        $reward = 0;
        $arr = [];
        $arr['level'] = [];
        $arr['same_level'] = [];

        $goods_info = Goods::find($goods_id);
        $level_reward = 0;
        switch ($goods_info['type'])
        {
            case 1:
                $level_reward = self::$base_level_reward;
                break;
            case 2:
                $level_reward = bcdiv(bcmul($goods_info['sale_amount'], self::$level_reward2_rate), Base::$hundred);
                break;
        }

        foreach ($parent_ids_array as $parent)
        {
            if($parent['level_id'] > $start_level_id)
            {
                $parent_level_id = $parent['level_id'] >= 5 ? 5 : $parent['level_id'];
                $diff_level = $parent_level_id - $start_level_id;
                $reward = bcmul(bcmul($level_reward, $diff_level), $goods_num);
                $arr['level'][] = [
                    'user_id'=>$parent['id'],
                    'level_id'=>$parent_level_id,
                    'reward'=>$reward,
                ];
                if($parent['level_id'] > 2 && $parent['level_id'] < 6)
                {
                    $user_parent_ids_str = str_replace('|', ',', substr_replace(substr_replace($parent['parent_ids'], '', 0, 1), '', -1, 1));
                    if($same_level_user = User::field('id, level_id, parent_ids')->whereIn('id', $user_parent_ids_str)
                        ->where('level_id', $parent['level_id'])
                        ->find())
                    {
                        $arr['same_level'][] = [
                            'user_id'=>$same_level_user['id'],
                            'level_id'=>$parent['level_id'],
                            'reward'=>bcmul(bcmul(self::$base_same_level_reward, $goods_num), $goods_num)
                        ];
                    }
                }

                $start_level_id = $parent_level_id;
            }
            if($start_level_id == 5)
            {
                //已经是合伙人
                break;
            }
        }
        return $arr;
    }

//    public function orderItem()
//    {
//        return $this->hasMany(OrderItem::class, 'order_id', 'id');
//    }
}